package com.zhihu.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zhihu.client.MessageClient;
import com.zhihu.dao.UserMapper;
import com.zhihu.dao.UserRepository;
import com.zhihu.pojo.User;
import com.zhihu.pojo.baseVo.BaseResult;
import com.zhihu.pojo.req.TbUserReq;
import com.zhihu.service.UserService;
import com.zhihu.utils.JwtUtils;
import com.zhihu.utils.MD5Util;
import com.zhihu.utils.RedisUtils;
import com.zhihu.utils.UploadUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.UUID;


/**
 * @author : zhangzheng
 * ClassName: UserServiceImpl
 * @date : 2021/9/3 15:23
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserRepository userRepository;
    @Autowired
    MessageClient messageClient;
    @Autowired
    RedisUtils redisUtils;

    @Autowired
    UserMapper userMapper;

       /**
     * 验证手机号是否已经注册
     * @param telephone
     * @return
     */
    @Override
    public BaseResult decideTel(String telephone) {
        if (telephone==null){
            return new BaseResult(1,"电话号码不能为空！");
        }
        //去数据库查询
        User byTelephone = userRepository.findByTelephone(telephone);
        System.out.println(byTelephone);
        if (byTelephone!=null){
            return new BaseResult(1,"手机号已被注册！");
        }
        return new BaseResult(0,"该手机号可用！");
    }

    /**
     * 短信发送
     * @param telephone
     * @return
     */
    @Override
    public BaseResult sendMsg(String telephone) {
        BaseResult baseResult = messageClient.sendMsg(telephone);
        if (baseResult!=null){
            return new BaseResult(0,"发送成功！");
        }else{
            return new BaseResult(1,"发送失败！");
        }
    }

    /**
     * 用户注册
     * @param tbUserReq
     * @return
     */
    @Override
    public BaseResult registry(TbUserReq tbUserReq) {
        //从数据库查出用户手机号信息
        User byTelephone = userRepository.findByTelephone(tbUserReq.getTelephone());
        //System.out.println(byTelephone);
        //判断是否已经被注册
        if (byTelephone!=null){
            return new BaseResult(1,"该手机号已被注册");
        }
        //判断验证码是否有效
        boolean b = redisUtils.hasKey(tbUserReq.getTelephone());
        if (!b){
            return new BaseResult(1,"验证码失效！");
        }
        //获取验证码
        Object o = redisUtils.get(tbUserReq.getTelephone());
        //System.out.println(o);
        if (!redisUtils.get(tbUserReq.getTelephone()).equals(o.toString())){
            return new BaseResult(1,"验证码错误！");
        }
        User user = new User();
        BeanUtils.copyProperties(tbUserReq,user);
        //md5密码的加密
        user.setPassword(MD5Util.getStringMD5(user.getPassword()));
        user.setImg("http://qyum6ugc6.hd-bkt.clouddn.com/%E7%9F%A5%E4%B9%8E%E5%A4%B4%E5%83%8F1.jpg");
        userRepository.saveAndFlush(user);
        return new BaseResult(0,"注册成功！");

    }

    /**
     * 用户登录密码
     * @param tbUserReq
     * @return
     */
    @Override
    public BaseResult login(TbUserReq tbUserReq) {
        //通过数据库查询用户手机号码
        User byTelephone = userRepository.findByTelephone(tbUserReq.getTelephone());
        System.out.println(byTelephone);
        //判断手机号是否已经被注册
        if (byTelephone==null){
            return new BaseResult(1,"用户不存在!");
        }
        //获取密码
        String password = tbUserReq.getPassword();
        if (password==null){
            return new BaseResult(1,"未设置密码");
        }
        if (!byTelephone.getPassword().equals(MD5Util.getStringMD5(password))){
            return new BaseResult(1,"密码错误");
        }
        //如果都没问题，进行登录操作 生成jwt 同时放入redis中
        JwtUtils jwtUtils = new JwtUtils();
        String jsonUser = jwtUtils.SignToken(JSONObject.toJSONString(byTelephone));
        //放置在redis中
        String token = UUID.randomUUID().toString();
        //将 jsonUser 为vale放置在redis中
        redisUtils.set(token,jsonUser);
        return new BaseResult(0,"登录成功",token);

    }

    /**
     * 用户通过短信验证登录
     * @param tbUserReq
     * @return
     */
    @Override
    public BaseResult loginMsg(TbUserReq tbUserReq) {
        User byTelephone = userRepository.findByTelephone(tbUserReq.getTelephone());
        if (byTelephone==null){
            return new BaseResult(1,"用户不存在");
        }
        Object o = redisUtils.get(tbUserReq.getTelephone());
        if (!redisUtils.get(tbUserReq.getTelephone()).equals(o.toString())){
            return new BaseResult(1,"验证码错误");
        }
        //如果都没问题，进行登录操作 生成jwt 同时放入redis中
        JwtUtils jwtUtils = new JwtUtils();
        String jsonUser = jwtUtils.SignToken(JSONObject.toJSONString(byTelephone));
        //放置在redis中
        String token = UUID.randomUUID().toString();
        //将 jsonUser 为vale放置在redis中
        redisUtils.set(token,jsonUser);
        return new BaseResult(0,"登录成功",token);
    }

    /**
     * 用户退出登录
     * @param request
     * @return
     */
    @Override
    public BaseResult loginOut(HttpServletRequest request) {
        //1.获取header中的token
        String token = request.getHeader("token");
        //2.验证redis
        boolean b = redisUtils.hasKey(token);
        if (!b){
            return new BaseResult(1,"用户信息已过期");
        }
        redisUtils.del(token);
        return new BaseResult(0,"退出成功！");
    }

    /**
     * 添加用户名和密码
     * @param tbUserReq
     * @return
     */
    @Override
    public BaseResult insertConsumer(@RequestBody TbUserReq tbUserReq) {
        //拿到用户注册的手机号
        String telephone = tbUserReq.getTelephone();
        System.out.println(tbUserReq);
        //根据注册手机号拿到用户信息
        User user = userMapper.findByTel(telephone);
        System.out.println(user);
        BeanUtils.copyProperties(tbUserReq,user);
        //md5密码的加密
        user.setPassword(MD5Util.getStringMD5(user.getPassword()));
        user.setUserName(user.getUserName());
        //添加
        userRepository.saveAndFlush(user);
        return new BaseResult(0,"OK");
    }

    /**
     * 在已经登录的状态下修改用户的资料
     * @param tbUserReq
     * @param request
     * @return
     */
    @Override
    public BaseResult updateInformation(TbUserReq tbUserReq, HttpServletRequest request) {
        //从token中解析出用户的对象
        String token = request.getHeader("token");
        System.out.println(token);
        //2.验证token
        boolean b = redisUtils.hasKey(token);
        if (!b){
            return new BaseResult(1,"用户信息已过期");
        }
        String jwtToken = redisUtils.get(token).toString();
        //转化为json字符串
        JwtUtils jwtUtils = new JwtUtils();
        String s = jwtUtils.VerifyToekn(jwtToken);
        System.out.println(s);
        //从json转为user实体
        User user = JSONObject.parseObject(s, User.class);
        System.out.println(user);
        //对指定字段进行添加
        user.setUserName(tbUserReq.getUserName());
        user.setAddress(tbUserReq.getAddress());
        user.setSex(tbUserReq.getSex());
        user.setInfo(tbUserReq.getInfo());
        user.setJob(tbUserReq.getJob());
        user.setJobExp(tbUserReq.getJobExp());
        user.setIntro(tbUserReq.getIntro());
        System.out.println(tbUserReq);
        User user1 = userRepository.saveAndFlush(user);
        System.out.println(user1);
        if (user1==null){
            return new BaseResult(1,"添加失败");
        }
        return new BaseResult(0,"添加成功");
    }

    /**
     * 用户信息查看
     * @param request
     * @return
     */
    @Override
    public BaseResult findUser(HttpServletRequest request) {
        //1.获取header中的token
        String token = request.getHeader("token");
        //2.验证
        boolean b = redisUtils.hasKey(token);
        if (!b){
            return new BaseResult(1,"用户信息已过期");
        }
        String jwtToken = redisUtils.get(token).toString();
        JwtUtils jwtUtils = new JwtUtils();
        String s = jwtUtils.VerifyToekn(jwtToken);
        //从json转为实体
        User user = JSONObject.parseObject(s, User.class);
        return new BaseResult(0,"查询成功！",user);
    }

    /**
     * 所有用户信息
     * @return List集合
     */
    @Override
    public List<User> findAllUsers() {
       List<User>  userList = userMapper.findAllUser();
        System.out.println(userList);
        return userList;
    }

    /**
     * 单个用户信息
     * @return user对象
     */
    @Override
    public BaseResult findUserById(Integer userId) {
        User user =userMapper.findUserById(userId);
        System.out.println(user);
        if (user==null){
            return new BaseResult(1,"查询失败");
        }
        return new BaseResult(0,"查询成功",user);
    }

    /**
     * 用户的密码的修改
     * @param tbUserReq
     * @return
     */
    @Override
    public BaseResult updateUser(TbUserReq tbUserReq,HttpServletRequest request) {
        //查看用户的手机号是否已经绑定
        User byTelephone = userRepository.findByTelephone(tbUserReq.getTelephone());
        //判断是否绑定
        if (byTelephone!=null){
            return new BaseResult(0,"手机号已经绑定");
        }
        //从token中解析出用户的对像
        String token = request.getHeader("token");
        //验证token
        boolean b = redisUtils.hasKey(token);
        if (!b){
            return new BaseResult(1,"用户token已过期");
        }
        //修改信息发送验证码进行验证
        Object o = redisUtils.get(tbUserReq.getTelephone());
        if (!redisUtils.get(tbUserReq.getTelephone()).equals(o.toString())){
            return new BaseResult(1,"验证码错误");
        }
        //获取token
        String jwToken = redisUtils.get(token).toString();
        JwtUtils jwtUtils = new JwtUtils();
        //解析token
        String s = jwtUtils.VerifyToekn(jwToken);
        //将s   json转成json对象
        User user = JSONObject.parseObject(s, User.class);
        //修改赋值
        //md5密码的加密
        user.setPassword(MD5Util.getStringMD5(user.getPassword()));
        user.setTelephone(tbUserReq.getTelephone());
        User user1 = userRepository.saveAndFlush(user);
        //修改token中的数据
        String s1 = jwtUtils.SignToken(JSONObject.toJSONString(user1));
        redisUtils.set(token,s1);
        return new BaseResult(0,"修改成功");
    }
//    /**
//     * 头像和背景图片上传
//     * @param file
//     * @return
//     */
//    @Override
//    public BaseResult upload(MultipartFile file) {
//        UploadUtils uploadUtils = new UploadUtils();
//        try {
//            String upload = uploadUtils.upload(file.getInputStream());
//            return new BaseResult(0,"上传成功！",upload);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return new BaseResult(1,"上传失败！");
//    }
}
